<?php

namespace app\home\controller;

// 引入前台公共控制器
use app\common\controller\Home;
// 引入邮件类
use app\common\library\Email;

class Business extends Home
{
    public function __construct()
    {
        parent::__construct();

        // 公共区域加载模型
        $this->BusinessModel = model('Business.Business');
        $this->PayModel = model('pay.Pay');
    }

    public $NoLogin = ['index'];

    // 会员模型
    protected $BusinessModel;

    protected $PayModel;

    // 会员首页
    public function index()
    {
        // 给一个模板渲染
        return $this->view->fetch();
    }

    // 基本资料
    public function profile()
    {
        if ($this->request->isPost()) {
            $data = [
                'id' => $this->view->business['id'],
                'nickname' => $this->request->param('nickname', '', 'trim'),
                'mobile' => $this->request->param('mobile', '', 'trim'),
                'gender' => $this->request->param('gender', '', 'trim'),
            ];

            $email = $this->request->param('email', '', 'trim');
            $password = $this->request->param('password', '', 'trim');
            $code = $this->request->param('code', '', 'trim');

            // 如果用户输入了密码，就修改密码
            if (!empty($password)) {
                // 重新生成密码盐
                $salt = randstr();

                $data['salt'] = $salt;
                $data['password'] = md5($password . $salt);
            }

            if ($email != $this->view->business['email']) {
                $data['email'] = $email;
                $data['auth'] = '0';
            }

            if (!empty($code)) {
                $parentpath = model('Region')->where(['code' => $code])->value('parentpath');

                if (!empty($parentpath)) {
                    $arr = explode(',', $parentpath);

                    $data['province'] = isset($arr[0]) ? $arr[0] : null;
                    $data['city'] = isset($arr[1]) ? $arr[1] : null;
                    $data['district'] = isset($arr[2]) ? $arr[2] : null;
                }
            }

            // 判断是否有图片上传
            if (isset($_FILES['avatar']) && $_FILES['avatar']['error'] == 0) {
                $result = upload_image('avatar');

                if (!$result['success']) {
                    $this->error($result['msg']);
                    exit;
                }

                $data['avatar'] = $result['data'];
            }

            $result = $this->BusinessModel->validate('common/Business/Business.profile')->isUpdate(true)->save($data);

            // 写入数据库失败
            if ($result = false) {
                $this->error($this->BusinessModel->getError());
                exit;
            }

            // 判断是否有旧图片，有则删除
            if (isset($data['avatar'])) {
                $old_avatar = '.' . $this->BusinessData['avatar'];
                is_file($old_avatar) && @unlink($old_avatar);
            }

            // 是否修改了手机号
            if ($data['mobile'] != $this->BusinessData['mobile']) {
                $cookie = [
                    'id' => $data['id'],
                    'mobile' => $data['mobile']
                ];

                cookie('business', $cookie);
            }

            $this->success('更新资料成功', url('home/business/index'));
            exit;
        }

        return $this->view->fetch();
    }

    // 邮箱验证
    public function email()
    {
        // 加载邮箱模型
        $EmsModel = model('common/Ems');

        if ($this->request->isAjax()) {
            $action = $this->request->param('action', '', 'trim');

            if ($action == 'send') {
                // 生成一个验证码
                $code = randstr(6);
                $email = $this->BusinessData['email'] ? trim($this->BusinessData['email']) : '';

                if (empty($email)) {
                    $this->error('邮箱地址为空');
                    exit;
                }

                // 开始事务
                $EmsModel->startTrans();

                //删除掉之前旧的验证码
                $EmsModel->where(['email' => $email])->delete();

                $data = [
                    'event' => 'auth',
                    'email' => $email,
                    'code' => $code,
                    'times' => 0,
                ];

                // 插入数据
                $ems = $EmsModel->save($data);

                if ($ems == false) {
                    $this->error('验证码发送失败');
                    exit;
                }

                // 邮件数据
                $name = config('site.name');
                $subject = "[$name] 邮箱验证";
                $maessage = "<div>您的邮箱验证码为：<b>$code</b></div>";

                // 实例化邮箱类
                $PhpMailer = new Email;

                $result = $PhpMailer
                    ->to($email)
                    ->subject($subject)
                    ->message($maessage)
                    ->send();

                if ($result) {
                    // 提交事务
                    $EmsModel->commit();
                    $this->success('验证码已发送，请注意查收');
                    exit;
                } else {
                    // 回滚事务
                    $EmsModel->rollback();
                    $this->error($PhpMailer->getError());
                    exit;
                }
            }
        }

        if ($this->request->isPost()) {
            // 过期时间
            $expire = 60 * 5;

            // 获取验证码
            $code = $this->request->param('code', '', 'trim');

            if (empty($code)) {
                $this->error('验证码不能为空');
                exit;
            }

            $email = $this->BusinessData['email'];

            if (empty($code)) {
                $this->error('邮箱不能为空');
                exit;
            }

            // 开始事务
            $EmsModel->startTrans();
            $this->BusinessModel->startTrans();

            // 查询验证码是否存在
            $where = ['email' => $email, 'code' => $code];
            $check = $EmsModel->where($where)->find();

            if (!$check) {
                $this->error('验证码错误');
                exit;
            }


            // 验证码是否过期
            if (time() > $check['createtime'] + $expire) {
                $this->error('验证码已过期');
                exit;
            }

            // 更新用户数据
            $data = [
                'id' => $this->BusinessData['id'],
                'auth' => '1'
            ];

            $BusinessRes = $this->BusinessModel->isUpdate(true)->save($data);

            if ($BusinessRes === false) {
                $this->error('用户邮箱认证状态更新失败');
                exit;
            }

            $EmsRes = $EmsModel->where($where)->delete();

            if ($EmsRes === false) {
                $this->BusinessModel->rollback();
                $this->error('验证码记录删除失败');
                exit;
            }

            if ($BusinessRes && $EmsRes) {
                // 提交事务
                $this->BusinessModel->commit();
                $EmsModel->commit();
                $this->success('用户邮箱认证成功', url('home/business/index'));
                exit;
            } else {
                $this->BusinessModel->rollback();
                $EmsModel->rollback();
                $this->error('用户邮箱认证失败');
                exit;
            }
        }

        return $this->view->fetch();
    }

    // 我的订单
    public function order()
    {
        if ($this->request->isAjax()) {
            $orderModel = model('Subject.Order');

            $business = $this->BusinessData;

            // 接收参数
            $page = $this->request->param('page', 1, 'trim');
            $limit = $this->request->param('limit', 10, 'trim');

            // 查询总数
            $count = $orderModel->where(['busid' => $business['id']])->count();

            $start = ($page - 1) * $limit;

            if (!$business) {
                $this->error('请先登录', url('home/business/index'));
                exit;
            }

            $orderList = $orderModel
                ->with(['subject'])
                ->where(['busid' => $business['id']])
                ->order('createtime desc')
                ->limit($start, $limit)
                ->select();

            if (empty($orderList)) {
                $this->error('暂无更多数据');
                exit;
            } else {
                $this->success('ok', null, [
                    'data' => $orderList,
                    'count' => $count
                ]);
                exit;
            }
        }


        return $this->view->fetch();
    }

    // 订单评价
    public function comment()
    {
        $SubjectModel = model('common/Subject/Subject');

        $business = $this->BusinessData;

        $pid = $this->request->param('pid', 0, 'trim');

        if (!$business) {
            $this->error('请先登录', url('home/business/index'));
            exit;
        }

        if ($this->request->isPost()) {
            $CommentModel = model('common/Subject/Comment');

            // 接收参数
            $content = $this->request->param('content', 1, 'trim');

            if (empty($content)) {
                $this->error('请输入评价内容');
                exit;
            }

            $data = [
                'content' => $content,
                'busid' => $business['id'],
                'subid' => $pid,
            ];

            // myPrinf($data);
            // exit;

            $commentResult = $CommentModel->save($data);

            if ($commentResult) {
                $this->success('评价成功', url('home/business/order'));
            } else {
                $this->error('评价失败');
            }
        }

        // 判断课程是否存在
        $subject = $SubjectModel->find($pid);

        if (!$subject) {
            $this->error('课程不存在', url('home/index/index'));
            exit;
        }

        $this->view->assign('subject', $subject);

        return $this->view->fetch();
    }

    // 消费记录
    public function record()
    {
        if ($this->request->isAjax()) {
            $recordModel = model('Business.Record');

            $business = $this->BusinessData;

            if (!$business) {
                $this->error('请先登录', url('home/business/index'));
                exit;
            }

            // 接收参数
            $page = $this->request->param('page', 1, 'trim');
            $limit = $this->request->param('limit', 10, 'trim');

            $start = ($page - 1) * $limit;

            // 查询总数
            $count = $recordModel->where(['busid' => $business['id']])->count();

            $orderList = $recordModel
                ->where(['busid' => $business['id']])
                ->order('createtime desc')
                ->limit($start, $limit)
                ->select();

            if (empty($orderList)) {
                $this->error('暂无更多数据');
                exit;
            } else {
                $this->success('ok', null, [
                    'data' => $orderList,
                    'count' => $count
                ]);
                exit;
            }
        }

        return $this->view->fetch();
    }

    //充值
    public function pay()
    {
        if ($this->request->isPost()) {
            $money = $this->request->param('money', 1, 'trim');

            //发送一个接口请求出去
            $host = config('site.cdnurl');
            $host = trim($host, '/');

            //完整的请求接口地址
            $api = $host . "/pay/index/create";

            //订单支付完成后跳转的界面
            $reurl = $host . '/home/business/pay';

            $callbackurl = $host . "/home/business/callback";

            //携带一个自定义的参数过去 转换为json类型
            $third = json_encode(['busid' => $this->view->business['id']]);

            //微信收款码
            $wxcode = config('site.wxcode');
            $wxcode = $host . $wxcode;

            //支付宝收款码
            $zfbcode = config('site.zfbcode');
            $zfbcode = $host . $zfbcode;

            //充值信息
            $PayData = [
                'name' => '余额充值',
                'third' => $third,
                'originalprice' => $money,
                //微信支付
                'paytype' => 0,
                'paypage' => 1,
                //支付宝支付
                // 'paytype' => 1,
                // 'paypage' => 2,
                'reurl' => $reurl,
                'callbackurl' => $callbackurl,
                'wxcode' => $wxcode,
                'zfbcode' => $zfbcode,
            ];

            //发起请求
            $result = httpRequest($api, $PayData);

            //有错误
            if (isset($result['code']) && $result['code'] == 0) {
                $this->error($result['msg']);
                exit;
            }

            echo $result;
            exit;
        }
        return $this->view->fetch();
    }
    // 充值成功跳转提醒
    public function notice()
    {
        $this->success('支付成功', url('home/business/pay'));
        exit;
    }
    //充值回调
    public function callback()
    {
        // 判断是否有post请求过来
        if ($this->request->isPost()) {
            // 获取到所有的数据
            $params = $this->request->param();


            // 充值的金额
            $price = isset($params['price']) ? $params['price'] : 0;
            $price = floatval($price);

            // 第三方参数(可多参数)
            $third = isset($params['third']) ? $params['third'] : '';

            // json字符串转换数组
            $third = json_decode($third, true);

            // 从数组获取充值的用户id
            $busid = isset($third['busid']) ? $third['busid'] : 0;

            // 支付方式
            $paytype = isset($params['paytype']) ? $params['paytype'] : 0;

            // 支付订单id
            $payid = isset($params['id']) ? $params['id'] : 0;

            $pay = $this->PayModel->find($payid);

            if (!$pay) {
                return json(['code' => 0, 'msg' => '支付订单不存在', 'data' => null]);
            }

            $payment = '';

            switch ($paytype) {
                case 0:
                    $payment = '微信支付';
                    break;
                case 1:
                    $payment = '支付宝支付';
                    break;
            }

            //判断充值金额
            if ($price <= 0) {
                return json(['code' => 0, 'msg' => '充值金额为0', 'data' => null]);
            }

            // 加载模型
            $BusinessModel = model('Business.Business');
            $RecordModel = model('Business.Record');

            $business = $BusinessModel->find($busid);

            if (!$business) {
                return json(['code' => 0, 'msg' => '充值用户不存在', 'data' => null]);
            }

            // 开启事务
            $BusinessModel->startTrans();
            $RecordModel->startTrans();

            // 转成浮点类型
            $money = floatval($business['money']);

            // 余额 + 充值的金额
            $updateMoney = bcadd($money, $price, 2);

            // 封装用户更新的数据
            $BusinessData = [
                'id' => $business['id'],
                'money' => $updateMoney
            ];

            // 自定义验证器
            $validate = [
                [
                    'money' => ['number', '>=:0'],
                ],
                [
                    'money.number' => '余额必须是数字类型',
                    'money.>=' => '余额必须大于等于0元'
                ]
            ];

            $BusinessStatus = $BusinessModel->validate(...$validate)->isUpdate(true)->save($BusinessData);

            if ($BusinessStatus === false) {
                return json(['code' => 0, 'msg' => $BusinessModel->getError(), 'data' => null]);
            }

            // 封装插入消费记录的数据
            $RecordData = [
                'total' => $price,
                'content' => "{$payment}充值了 $price 元",
                'busid' => $business['id']
            ];

            // 插入
            $RecordStatus = $RecordModel->validate('common/Business/Record')->save($RecordData);

            if ($RecordStatus === false) {
                $BusinessModel->rollback();
                return json(['code' => 0, 'msg' => $RecordModel->getError(), 'data' => null]);
            }

            if ($BusinessStatus === false || $RecordStatus === false) {
                $BusinessModel->rollback();
                $RecordModel->rollback();
                return json(['code' => 0, 'msg' => '充值失败', 'data' => null]);
            } else {
                $BusinessModel->commit();
                $RecordModel->commit();

                // 订单号：\r\n
                // 金额:50元
                // 支付方式：
                // 时间，
                return json(['code' => 1, 'msg' => '充值成功', 'data' => null]);
            }
        }
    }
}
